import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView, Platform, KeyboardAvoidingView, StyleSheet, Image, Keyboard } from "react-native";
import { style } from '../../../../theme/style';
import { orderBlockStyle } from '../_common/style';
// import { AddLongBtn } from '../_components/AddLongBtn.js';
// import { TitleView } from '../_components/TitleView.js';
// import { SelectComponent } from '../_components/SelectComponent';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import OrderAPIService from '../_common/OrderAPIService';
import OrderCreactService from '../_common/service';
import { CURRENCY } from '../../../../utils/helper';
import ToastUtil from '../../../../utils/toast';
import Utils from '../../../../utils/utils';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';
import { Button } from '../../../../components/form/button';
import { FormItem } from '../../../../components/form/formItem';
import { GLOBAL } from '../../../../config/global';
import Dictionary from '../../../../utils/dictionary';
import ProductSelect from '../../../product/modals/ProductSelect';
import moment from 'moment';
import { DatePicker, CustomPicker } from 'react-native-pickers';
import { SelectOnffBlock } from "../_block/SelectOnffBlock";
import OrderCreateMethods from '../../OrderCreateMethods';
import { OriginalAddress } from "../../../../component/ui/OriginalAddress";

const QH_PRICE = '18092816325848817279486401'; //框架结算公式为“中化泉州石化出厂价“
const checkOnImg = require('../../../../imgs/checkOn.png');
const checkOffImg = require('../../../../imgs/checkOff.png');

/*
*orderType  销售->S   采购->P
*periodType 长约->L   普通->S
*tCode   现货->S   长约->L  远期->F   代理->A   E->远期执行  C->背靠背
*/
const scale = GLOBAL.SCALE;
const quantityReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,3})?$/;
let pageData;
export class QHNewProductFormPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '新增商品',
      headerTintColor: '#272727',
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#272727' />,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      },
      headerStyle: {
        elevation: 0,
        backgroundColor: '#F5F5F5',
        borderBottomWidth: 0,
      },
    }
  };
  requesting;
  constructor(props) {
    super(props);
    this.jumpPage = OrderCreactService.jump.bind(this);
    this.resetPage = OrderCreactService.reset.bind(this);
    pageData = {};
    this.pushIndex = -1;
    this.state = {
      status: 'data',
      goodsModal: false,
      includeNextMonth: false,
      quantityAppointData: [],
      baseSettleIndex: -1,//基准月 ....
      baseSettleModal: false,
      baseSettleData: [],
      modalVisible: false //原产地
    }

    this.goodsData = {}
    this.showData = {};
    this.customerFunds = 0;
    this.QHStore = '';
    this.isCustom = false; //基准月是否显示
  }

  async	componentWillMount() {
    this.currentMonth = moment().format('YYYYMM');
    this.nextMonth = moment().add('months', 1).format('YYYYMM');
    this.initData();
  }

  componentWillUnmount() {

  }

  initData = async () => {
    let { titleName, tCode, orderType, companyId, companyName, baseDateSettle, currency, editData, longFrameIdArr, productList, productIndex, groupOnoff } = this.props.navigation.state.params || {};
    pageData = { titleName, tCode, orderType, companyId, companyName, baseDateSettle, currency };
    console.log('this.props.navigation.state.params', this.props.navigation.state.params)
    let { label, text } = CURRENCY.getUnit(currency);
    let currentProductList = JSON.parse(JSON.stringify(productList));
    OrderAPIService.initAPIs(tCode, orderType);
    this.groupOnoff = groupOnoff || null;
    this.unitSymbol = label;
    this.unit = text;
    this.tCode = tCode;
    this.editData = editData;
    this.productList = currentProductList;
    this.productIndex = productIndex;
    this.longFrameIdArr = longFrameIdArr || '';
    await this.initDictionary();
    if (editData) this.initGoodsData(editData)
    this.getCustomerFunds();//获取客户资金
  }

  //数据字典-初始化
  async initDictionary() {
    this.setState({ status: 'loading' })
    let quantityAppointData = await Dictionary.get('GOODS_QUALITY_STANDARD');
    this.setState({
      quantityAppointData: quantityAppointData || [],
      status: 'data'
    });
  }

  //获取客户资金
  getCustomerFunds = async () => {
    let responseData = await OrderAPIService.getCustomerFunds({ companyId: pageData.companyId, currency: pageData.currency });
    this.customerFunds = responseData.value;
  }

  initGoodsData = async (data) => {
    console.log('data-123-商品初始化', data)
    this.setState({ status: 'loading' })
    let { logisticsPrice } = this.props.navigation.state.params || {};
    let { quantityAppointData } = this.state;
    if (data) {
      this.goodsData = data;
      this.goodsData.goodsId = data.goodsId;
      this.goodsData.goodsName = data.goodsName;
      this.goodsData.transLevel = data.transLevel;
      this.goodsData.longFrameId = data.longFrameId;
      this.goodsData.logisticsPrice = logisticsPrice || 0;
      this.goodsData.priceFormlaId = data.priceFormlaId;//	结算价
      this.goodsData.priceFormlaName = data.priceFormlaName;
      this.goodsData.quantity = data.quantity || '';
      this.goodsData.longItemId = data.longItemId || '';
      this.goodsData.itemId = data.itemId || '';
      this.goodsData.orderPlanMonth = data.orderPlanMonth == this.nextMonth ? this.nextMonth : this.currentMonth;
      this.goodsData.checkRebateFlag = data.checkRebateFlag;
      this.goodsData.rebateId = data.rebateId || null;
      this.goodsData.makePlace = data.makePlace || null;
      this.goodsData.makeAreaId = data.makeAreaId || null;
      if (data.qualityStd && quantityAppointData && quantityAppointData.length > 0) {
        quantityAppointData.forEach((item, index) => {
          if (item.dictKey == data.qualityStd) {
            this.goodsData.qualityStdDesc = item.dictName;
          }
        })
      }
      this.setState({ includeNextMonth: this.goodsData.orderPlanMonth == this.nextMonth })
    } else {
      this.goodsData.orderPlanMonth = this.goodsData.orderPlanMonth || this.currentMonth
    }
    if (this.goodsData.goodsId) {
      await this.getGoodsQuantity();
      this.getSuggestPrice();
    }
    if (this.goodsData.priceFormlaId && this.goodsData.priceFormlaId != QH_PRICE) { // 根据价格公式获取基准日期 基准月
      this._getBase()
    }
    this.setState({ status: 'data' })
  }

  // 获取今日现货价
  getSuggestPrice = async () => {
    let subData = {
      orderId: this.longFrameIdArr,
      orderItemInfo: {
        orderId: this.longFrameIdArr,
        itemId: this.goodsData.longItemId,
        goodsId: this.goodsData.goodsId,
        longOrderId: this.longFrameIdArr
      }
    }
    let respData = await OrderAPIService.getOrderOtherPrice(subData) || {};
    this.goodsData.suggestedPrice = respData.suggestedPrice || 0;
    console.log('现货价获取,', this.goodsData.suggestedPrice)
  }

  getGoodsQuantity = async () => {
    let { isUnite } = this.props.navigation.state.params || {};
    let params = {
      orderId: this.longFrameIdArr,
      orderType: pageData.orderType,
      isUnite: 1,
      orderPlanMonth: this.goodsData.orderPlanMonth,
      goodsId: this.goodsData.goodsId,
      itemId: this.goodsData.longItemId,
      companyId: pageData.companyId
    }
    let res = await HTTP.POST(API_GENERATE(API.GET_FRAME_GOODS_QUANTITY), params);
    if (!res) return;
    this.showData.remainPlanQuantity = res.remainPlanQuantity; // 计划量
    this.showData.stockQuantity = res.stockQuantity; // 分公司敞口库存
    this.showData.stockQuantityMax = res.stockQuantityMax; // 敞口上限
    this.showData.longQuantity = res.longQuantity; // 长约总量
    this.showData.remainLongQuantity = res.remainLongQuantity; // 剩余量
  }

  // 点击选择商品
  selectProduct = () => {
    this.setState({ goodsModal: true })
  }

  //商品取消按钮
  _cancelPress = () => {
    this.setState({ goodsModal: false })
  }

  _confirmPress = (data) => {
    if (data.length > 0) {
      let lastGoodsId = this.goodsData.goodsId;
      if (lastGoodsId == data[0].goodsId) return;
      this.goodsData.bizTeamId = data[0].goodsItem.bizTeamId;
      this.goodsData.bizLineId = data[0].goodsItem.bizLineId;
      this.goodsData.goodsId = data[0].goodsId;
      this.goodsData.goodsName = data[0].goodsName;
      this.goodsData.transLevel = data[0].transLevel;
      this.goodsData.longItemId = data[0].itemId || '';
      this.goodsData.qhPriceChangeFlag = data[0].goodsItem.qhPriceChangeFlag;
      this.goodsData.priceFormlaId = data[0].goodsItem.priceFormlaId;//	结算价
      this.goodsData.priceFormlaName = data[0].goodsItem.priceFormulaDesc;
      if (this.goodsData.priceFormlaId && this.goodsData.priceFormlaId != QH_PRICE) { // 根据价格公式获取基准日期 基准月
        this._getBase();
      }
      this.initGoodsData()
      this.setState({ goodsModal: false })
    } else {
      this.setState({ goodsModal: false })
    }
  }

  // 商品参数
  _getGoodsParams = () => {
    let { creditLevelBuy, creditLevelSell } = this.props.navigation.state.params || {};
    let params = {
      orderId: this.longFrameIdArr || ''
    };
    return params
  }

  save = () => {
    let { remainPlanQuantity, longQuantity, remainLongQuantity } = this.showData
    let { logisticsPrice } = this.props.navigation.state.params || {};
    if (!this.goodsData.goodsId) {
      ToastUtil.showWarning('请选择商品');
      return false
    }
    if (!this.goodsData.quantity) {
      ToastUtil.showWarning('请输入销售量');
      return false
    }
    if (this.goodsData.quantity <= 0) {
      ToastUtil.showWarning('数量必须大于0');
      return false
    }
    if (!quantityReg.test(this.goodsData.quantity)) {
      ToastUtil.showWarning(`请输入正确的数量(最多3位小数)`);
      return
    }
    if (!this.goodsData.suggestedPrice || this.goodsData.suggestedPrice <= 0) {
      ToastUtil.showWarning('该商品暂无现货价');
      return false
    }
    if (!remainPlanQuantity || this.goodsData.quantity > remainPlanQuantity) {
      ToastUtil.showWarning(`数量已超出计划量`);
      return
    }
    if (!longQuantity || this.goodsData.quantity > longQuantity) {
      ToastUtil.showWarning(`数量已超出框架剩余量`);
      return
    }
    if (!remainLongQuantity || this.goodsData.quantity > remainLongQuantity) {
      ToastUtil.showWarning(`数量已超出剩余量`);
      return
    }
    //优惠价格
    if (OrderCreateMethods._rebateValidation(this.goodsData)) {
      ToastUtil.showWarning(`请输入优惠价格`);
      return;
    }
    if (this.goodsData.ysPercent === '' || this.goodsData.ysPercent === null || this.goodsData.ysPercent === undefined) {
      ToastUtil.showWarning('请输入溢短装率');
      return
    } else if (this.goodsData.ysPercent < 0 || this.goodsData.ysPercent > 20) {
      ToastUtil.showWarning('请输入大于等于0且小于等于20的数字');
      return
    }
    if (!this.goodsData.makeAreaId) {
      ToastUtil.showWarning('请选择原产地');
      return
    }
    this.goodsData.logisticsPrice = logisticsPrice || 0;
    // 液化气商品用 壹化网
    if (this.goodsData.qhPriceChangeFlag == '1') {
      this.goodsData.isQhFlag = true;
    } else {
      this.goodsData.isQhFlag = false;
    }
    this.productList[this.productIndex] = this.goodsData;
    console.log('this.productList', this.productList);
    this.props.navigation.state.params.callBack(this.productList);
    this.props.navigation.goBack();
  }

  //数量输入
  _quantityFn = (str) => {
    this.goodsData.quantity = str;
  }

  // 选择下月采购/销售量
  selectNextMonthQuantity = () => {
    Keyboard.dismiss();
    let includeNextMonth = !this.state.includeNextMonth;
    this.goodsData.orderPlanMonth = includeNextMonth ? this.nextMonth : this.currentMonth;
    this.initGoodsData();
    this.setState({ includeNextMonth })
  }


  // 选择基准月（公式）
  _baseSettlCallBack = (index) => {
    this.goodsData.formulaSettleName = this.state.baseSettleData[index].dictName;
    this.goodsData.formulaSettleValue = this.state.baseSettleData[index].dictKey;
    if (this.goodsData.formulaSettleValue == 'CUSTOM_DAY' || this.goodsData.formulaSettleValue == 'CUSTOM_MONTH') { // 是否显示自定义
      this.isCustom = true;
    } else {
      this.isCustom = false;
      this.goodsData.formulaCustomValue = null;
    }
    this.setState({
      baseSettleModal: false,
      baseSettleIndex: index
    })
  }

  //获取基准月
  _getBase = async () => {
    let { priceFormlaId } = this.goodsData;
    if (!priceFormlaId) return;
    let responseData = await HTTP.POST(API_GENERATE(API.NEW_ORDER_SETTLEDETAIL), { formulaId: priceFormlaId, isFilter: true });
    if (responseData) {
      this.goodsData.formulaSettleType = responseData.cycleType;
      this.goodsData.baseSettleTitle = this._getBaseSettleTitle(responseData.cycleType);
      if (this.goodsData.formulaSettleType == 'FIXED_DATE_RANGE') {
        this.goodsData.formulaSettleValue = responseData.detailVOList[0].dictKey;
        this.goodsData.formulaCustomValue = responseData.periodDay;
      }
      this.setState({
        baseSettleData: responseData.detailVOList
      })
    }
  }


  /**
  * 结算方式
  */
  //private String formulaSettleType;
  /**
   * 结算方式值
   */
  //private String formulaSettleValue;

  /**
   * 结算方式自定义值
   */
  //private String formulaCustomValue;

  _getBaseSettleTitle = (strKey) => {
    //BASE_DATE    基准日
    //FIXED_DATE_RANGE  日期范围
    //MONTHLY_AVG  基准月
    let title = '';
    if (strKey == 'BASE_DATE') {
      title = '基准日';
    } else if (strKey == 'MONTHLY_AVG') {
      title = '基准月';
    } else {
      title = '日期范围';
    }
    return title;
  }

  _getYear = () => {
    let arrYear = [];
    for (let i = 2000; i < 2080; i++) {
      arrYear.push(i)
    }
    return arrYear || [];
  }

  //基准日清空
  _clearDay = (dictKey) => {
    this.goodsData.formulaSettleType = null;
    this.goodsData.formulaSettleValue = null;
    this.goodsData.formulaCustomValue = null;
    this.goodsData.formulaSettleName = null;
    this.goodsData.baseSettleTitle = null;
    if (dictKey == '1') { // 如果一口价
      this.isCustom = false;
    }
  }

  _openModal = () => {
    this.setState({
      baseSettleModal: true
    })
  }

  _closeModal = () => {
    this.setState({
      baseSettleModal: false
    })
  }

  _SelectCallBack = (callData) => {
    console.log("checkRebateFlag-callback-aaa-bbb-ccc", callData);
    this.goodsData = OrderCreateMethods._callRebate(callData, this.goodsData);
    console.log("sendData", this.goodsData);
  }

  //原产地-回调
  _addressCallback = (addressData) => {
    console.log("addressData", addressData)
    this.goodsData.makeAreaId = addressData.makeAreaId;
    this.goodsData.makePlace = addressData.makePlace;
    this.setState({
      ls: true
    })
  }

  //原产地 - 关闭弹框
  _closeModal = () => {
    this.setState({
      modalVisible: false
    })
  }


  render() {
    let { goodsName, quantity, priceFormlaName, goodsId, qualityStdDesc, checkRebateFlag, priceType, rebateId, makePlace } = this.goodsData || {};;
    let { status, goodsModal, includeNextMonth, priceIsVisible, baseSettleIndex, baseSettleModal, baseSettleData, modalVisible } = this.state;
    let { titleName, orderType, companyId } = pageData || {};
    let { logisticsPrice, ysPercent } = this.props.navigation.state.params || {};
    let { remainPlanQuantity, stockQuantity, stockQuantityMax, longQuantity, remainLongQuantity } = this.showData
    let isSeller = orderType == 'S';
    let ProductSend = [];
    if (this.goodsData.goodsId) {
      ProductSend.push({ goodsId: this.goodsData.goodsId, goodsName: this.goodsData.goodsName, transLevel: this.goodsData.transLevel })
    }
    return (
      <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={74}>
        <ScrollView style={styles.scrollWrap} keyboardShouldPersistTaps={'handled'} showsVerticalScrollIndicator={false}>
          <FormItem border type={'select'} label={'商品'} value={goodsName} placeHolder={'请选择商品'} handleCallBack={this.selectProduct} required />
          {(goodsId && companyId) ? <SelectOnffBlock params={{ companyId, goodsId, priceType, longOrderId: this.longFrameIdArr, tCode: this.tCode }} data={{ checkRebateFlag: checkRebateFlag || false, rebateId }} callBack={this._SelectCallBack} /> : null}
          <View>
            <FormItem border keyboardType='numeric' type={'input'} label={`销售量${includeNextMonth ? '(下月)' : '(当月)'}`} rightText={'吨'} value={quantity} placeHolder={`请输入数量`} handleCallBack={this._quantityFn} required />
            {
              goodsId ? (
                <View style={{ paddingLeft: 22 * scale, paddingRight: 22 * scale }}>
                  <View style={styles.infoWrap}>
                    <View><Text style={styles.info}>{includeNextMonth ? '下月' : '当月'}剩余计划量：{remainPlanQuantity || '--'}吨</Text></View>
                    <View><Text style={styles.info}>
                      分公司敞口库存：{stockQuantity || '--'}吨
                      {!isSeller ? <Text style={styles.info}>，敞口上限：{stockQuantityMax || '--'}吨</Text> : null}
                    </Text>
                    </View>

                    <View>
                      <Text style={styles.info}>长约总量：{longQuantity || '--'}吨
                        <Text style={styles.info}>，剩余量：{remainLongQuantity || '--'}吨</Text>
                      </Text>
                    </View>
                  </View>
                </View>
              ) : null
            }

            {/* 切换是否含下月采购*/}
            <TouchableOpacity activeOpacity={.6} style={styles.selectWrap} onPress={() => { this.selectNextMonthQuantity() }}>
              <Image style={{ marginRight: 4 * scale }} source={includeNextMonth ? checkOnImg : checkOffImg} />
              <Text style={includeNextMonth ? { opacity: 1 } : { opacity: .65 }}>使用下月计划量</Text>
            </TouchableOpacity>

            {/* 结算公式 */}
            <FormItem type={'mutiInput'} label={'结算公式'} value={priceFormlaName} editable={false} />
            {
              (!this.goodsData.formulaSettleType) ? null : (
                this.goodsData.formulaSettleType == 'FIXED_DATE_RANGE' ? null : <FormItem required border type={'select'} label={this.goodsData.baseSettleTitle} value={this.goodsData.formulaSettleName} placeHolder={'请选择'} handleCallBack={() => { this._openModal() }} />
              )
            }
            {(this.isCustom || this.goodsData.formulaCustomValue) ? (this.goodsData.formulaSettleType == 'FIXED_DATE_RANGE' ? <FormItem inputStyle={{ width: 190 * scale }} required border type={'input'} disable={true} label={this.goodsData.baseSettleTitle} value={this.goodsData.formulaCustomValue} editable={false} /> : <FormItem type={'select'} label={this.goodsData.formulaSettleType == 'BASE_DATE' ? '自定义日期' : '自定义月份'} value={this.goodsData.formulaCustomValue} placeHolder={'请选择'} handleCallBack={() => { this.DatePicker.show() }} required />) : null}
            {
              this.goodsData.priceFormlaId === QH_PRICE ? <View style={{ marginTop: 10 * scale }}>
                <FormItem type={'input'} label={'基准月'} value={"开单月"} editable={false} />
              </View> : null
            }
            <FormItem type={'input'} label={'品质约定'} value={qualityStdDesc} editable={false} />
            <FormItem type={'input'} disable={true} label={'溢短装率'} value={ysPercent} editable={false} border rightText={"%"} />
            {/* 原产地 */}
            <FormItem border type={'select'} label={'原产地'} value={makePlace} placeHolder={'请选择原产地'} handleCallBack={() => { this.setState({ modalVisible: true }) }} required />
          </View>

        </ScrollView>

        <View style={styles.btnWarp}>
          <Button text={'添加'} width={300} height={34} onPress={this.save} />
        </View>
        {/* 商品选择弹窗 */}
        {
          (companyId != '' && goodsModal) ? (<ProductSelect
            confirmPress={this._confirmPress}
            cancelPress={this._cancelPress}
            sendData={this._getGoodsParams()}
            mainCheckData={ProductSend}
            groupOnoff={this.groupOnoff}
            tCode={this.tCode}
            modalVisible={goodsModal} />) : null
        }
        {
          status != 'data' ? (<View style={orderBlockStyle.statusStyle}><PageStatusIndex status={status} /></View>) : null
        }

        {/* 选择基准月 */}
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={baseSettleIndex} title="请选择" listData={baseSettleData} selectCallBack={this._baseSettlCallBack} />
        )} isVisible={baseSettleModal} closeCallballFn={() => { this._closeModal({ baseSettleModal }) }} />
        {/* 基准日弹框 */}

        <DatePicker
          key={new Date().getTime()}
          column={this.goodsData.formulaSettleType === 'MONTHLY_AVG' ? 2 : false} //代表显示列数
          HH={false}
          mm={false}
          ss={false}
          unit={['年', '月', '日']}
          endYear={2080}
          onPickerConfirm={(valueArr) => {
            let valueArrNew = [];
            let valueArrMonth = [];
            valueArr && valueArr.forEach((item, index) => {
              let lsItem = item.slice(0, item.length - 1);
              lsItem = Utils.zeroPadding(lsItem)
              valueArrNew.push(lsItem);
              if (index != valueArr.length - 1) {
                valueArrMonth.push(lsItem);
              }
            })
            if (this.goodsData.formulaSettleType == 'MONTHLY_AVG') { // 基准月
              this.goodsData.formulaCustomValue = valueArrMonth.join('-');
              this.goodsData.formulaCustomValue = this.goodsData.formulaCustomValue.substring(0, 7);
            } else {
              this.goodsData.formulaCustomValue = valueArrNew.join('-');
              this.goodsData.formulaCustomValue = this.goodsData.formulaCustomValue.substring(0, 10);
            }
            this.setState({ ls: true })
          }}
          onPickerCancel={() => {
            console.log('cancel')
          }}
          ref={ref => this.DatePicker = ref} />
        {
          modalVisible ? <OriginalAddress
            modalVisible={modalVisible}
            closeModal={this._closeModal}
            params={{ tradeType: 'I' }}
            addressCallback={this._addressCallback}
          /> : null
        }
      </KeyboardAvoidingView>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  scrollWrap: {
    flex: 1,
    backgroundColor: '#fff',
    borderRadius: 4 * scale,
  },
  btnWarp: {
    height: 72 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  infoWrap: {
    marginBottom: 8 * scale,
    marginTop: 8 * scale
  },
  info: {
    color: '#F66464',
    fontSize: 13 * scale,
    marginTop: 4 * scale
  },
  selectWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
    paddingTop: 14 * scale,
    paddingBottom: 14 * scale,
    marginRight: 24.5 * scale,
  },
})
